package cn.com.xuxiaowei.client.utils;

import cn.com.xuxiaowei.client.intercptor.ClientLoginInterceptor;
import org.apache.cxf.ext.logging.LoggingInInterceptor;
import org.apache.cxf.ext.logging.LoggingOutInterceptor;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.message.Message;

import java.util.List;

/**
 * CXF 客户端 工具类
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
public class CxfClientUtils {

    private CxfClientUtils() {
    }
    /**
     * 创建 CXF 客户端
     *
     * @param address      地址
     * @param serviceClass （WebService响应结果）服务接口
     * @param <T>          泛型
     * @return 返回 （WebService响应结果）服务接口
     */
    public static <T> T create(String address, Class<T> serviceClass) {
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();

        jaxWsProxyFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
        jaxWsProxyFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());

        jaxWsProxyFactoryBean.setAddress(address);
        jaxWsProxyFactoryBean.setServiceClass(serviceClass);
        @SuppressWarnings("all")
        T service = (T) jaxWsProxyFactoryBean.create();
        return service;
    }

    public static <T> T create(String address, Class<T> serviceClass, String username, String password) {
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();

        List<Interceptor<? extends Message>> inInterceptors = jaxWsProxyFactoryBean.getInInterceptors();
        inInterceptors.add(new LoggingInInterceptor());

        List<Interceptor<? extends Message>> outInterceptors = jaxWsProxyFactoryBean.getOutInterceptors();
        outInterceptors.add(new LoggingOutInterceptor());
        outInterceptors.add(new ClientLoginInterceptor(username, password));

        jaxWsProxyFactoryBean.setAddress(address);
        jaxWsProxyFactoryBean.setServiceClass(serviceClass);
        @SuppressWarnings("all")
        T service = (T) jaxWsProxyFactoryBean.create();
        return service;
    }

}
